package com.gitee.qdbp.general.common.biz.sms.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitee.qdbp.able.exception.ServiceException;
import com.gitee.qdbp.able.result.ResponseMessage;
import com.gitee.qdbp.general.common.api.sms.model.ISmsTemplate;
import com.gitee.qdbp.general.common.error.GeneralErrorCode;
import com.gitee.qdbp.tools.http.HttpException;
import com.gitee.qdbp.tools.http.HttpTools.HttpFormImpl;
import com.gitee.qdbp.tools.http.HttpUrl;
import com.gitee.qdbp.tools.http.HttpUrl.HostUrl;
import com.gitee.qdbp.tools.http.RemoteServiceException;
import com.gitee.qdbp.tools.utils.StringTools;

/**
 * 叮咚云短信服务接口<br>
 * http://wiki.dingdongcloud.com/doku.php
 *
 * @author zhaohuihua
 * @version 160831
 */
// @Service // 这个Service在spring的xml文件中配置, 因为有些平台不需要短信功能
public class DdcSmsService extends BaseSmsService {

    private static final Logger log = LoggerFactory.getLogger(DdcSmsService.class);

    // 编码格式, 发送编码格式统一用UTF-8
    private static String ENCODING = "UTF-8";

    private Http http;

    public DdcSmsService() {
        this.properties = "settings/sms/sms.ddc.txt";
    }

    @Override
    @PostConstruct
    public void init() {
        super.init();
        this.http = new Http(config.getString("resultcode.success"));
    }

    @Override
    public String send(String phone, ISmsTemplate template, Object... args) throws ServiceException {

        utils.check(phone, template.name());

        String msg = "Failed to send Short Message.";

        String host = config.getString("sms.service.url");

        String type = config.getString("template." + template.name() + ".type", false);
        String uri;
        if ("validcode".equals(type)) { // 验证码短信
            uri = config.getString("sms.validcode.uri");
        } else { // 通知短信
            uri = config.getString("sms.notify.uri");
        }

        Map<String, Object> map = new HashMap<String, Object>();
        for (int i = 0; i < args.length; i++) {
            map.put(String.valueOf(i + 1), args[i]);
        }

        // 签名
        String signature = config.getString("sms.signature");
        // 短信内容
        String content = config.getString("template." + template.name());
        // 替换占位符
        content = StringTools.format(content, map);
        // 前面增加签名
        content = signature + content;
        try {
            // UTF-8编码
            content = URLEncoder.encode(content, ENCODING);
        } catch (UnsupportedEncodingException ignore) {
        }

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("apikey", config.getString("auth.apikey"));
        params.put("mobile", phone);
        params.put("content", content);

        String result;
        try {
            result = http.query(new HostUrl(host).post(uri), params, String.class);
        } catch (HttpException e) {
            log.error(msg + " HTTP request exception.", e);
            throw new ServiceException(GeneralErrorCode.SMS_SEND_ERROR);
        }

        return result;
    }

    @Override
    public Double balances() throws ServiceException {

        String msg = "Failed to get sms balances.";

        String host = config.getString("sms.service.url");
        String uri = config.getString("sms.balances.uri");

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("apikey", config.getString("auth.apikey"));

        // { "code":1, "msg":"成功", "result":"10" }
        Double number;
        try {
            number = http.query(new HostUrl(host).post(uri), params, Double.class);
        } catch (HttpException e) {
            log.error(msg + " HTTP request exception.", e);
            throw new ServiceException(GeneralErrorCode.SMS_BALANCES_ERROR);
        }

        return number;
    }

    /**
     * 叮咚云HTTP请求工具
     *
     * @author zhaohuihua
     * @version 160831
     */
    private static class Http extends HttpFormImpl {

        private String succCode;

        public Http(String succCode) {
            this.succCode = succCode;
        }

        protected ResponseMessage parseResult(HttpUrl hurl, String string) throws RemoteServiceException, Exception {
            // { "code":1, "msg":"成功", "result":"10" }
            JSONObject json = JSON.parseObject(string);
            ResponseMessage result = new ResponseMessage();
            result.setCode(json.getString("code"));
            result.setMessage(json.getString("msg"));
            result.setBody(json.getString("result"));

            if (succCode.equals(result.getCode())) {
                return result;
            } else {
                throw new RemoteServiceException(result.getCode(), result.getMessage());
            }
        }
    }

}
